<?php
/**
 * User: Julien
 * Date: 3/09/13
 * Time: 20:45
 */

class Application_Service_MailSender
{
    private $recipientAddress;
    private $recipientName;

    /**
     * Construct the object
     */
    public function __construct()
    {
        $options = Zend_Registry::get('Zend_Application_Options');
        $configParams = $options['mailer'];

        $this->recipientAddress = $configParams['recipientAddress'];
        $this->recipientName = $configParams['recipientName'];
    }

    /**
     * @param $sender
     * @param $message
     * @param $subject
     * @return bool
     * @throws Exception
     */
    public function send($sender, $message, $subject)
    {
        if (empty($sender)) {
            throw new Exception('A mail cannot be sent by nobody');
        }

        if (empty($message)) {
            throw new Exception('A message is mandatory');
        }

        if (empty($subject)) {
            $subject = "(sans sujet)";
        }

        if (Application::isDevelopment()) {
            $subject = '[TEST] ' . $subject;
        }

        $headers = $this->_setHeader($sender);
        $to = $this->recipientName . ' <' . $this->recipientAddress . '>';

        if (Application::isDevelopment()) {
            //Do not send the mail in local/dev envs
            $logMessage = "Mail must be sent, here are the details :" . "\n" .
                implode("\n", array(
                    "- to: " . $to,
                    "- subject: " . $subject,
                    "- message: " . $message,
                    "- headers: " . $headers
                )
            );
            Application::getLogger()->log($logMessage, LOG_DEBUG);

            return true;
        } else {
            return mail(
                $to,
                $subject,
                $message,
                $headers
            );
        }
    }

    /**
     * @return string
     */
    private function _setHeader($sender)
    {
        return
        'From: ' . $sender . "\r\n" .
        'Reply-To: ' . $sender . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
    }
}